package com.amumu.drama.common.base.mapstruct.ext;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * MapStruct映射扩展接口，处理String和List<XXX>的转换（需要字段名相同，若不相同则需要后置处理）
 * <p>
 * 例: public interface xxxMapping extends BaseMapping<xxxDO, xxxDTO>, StringToAnyListMapping
 */
public interface StringToAnyListMapping {

    /** 分隔符，默认英文逗号 */
    default String getSeparatorChars_stringToAnyListMapping() {//名字长纯粹为了继承多个Mapping时不冲突
        return ",";
    }

    /** 数组转String的时候是否忽略Null元素，默认true */
    default boolean skipNullOnJoinString_stringToAnyListMapping() {
        return true;
    }

    /** String转数组时候是否忽略空字符串，默认true */
    default boolean omitEmptyStringsOnSplit_stringToAnyListMapping() {
        return true;
    }

    /** String转List<String> */
    default List<String> stringToStringList(String val) {
        if (StringUtils.isBlank(val)) {
            return new ArrayList<>();
        }

        Splitter splitter = Splitter.on(getSeparatorChars_stringToAnyListMapping()).trimResults();
        if (omitEmptyStringsOnSplit_stringToAnyListMapping()) {
            splitter = splitter.omitEmptyStrings();
        }
        return splitter.splitToList(val);
    }

    /** List<String>转String */
    default String stringListToString(List<String> list) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return StringUtils.EMPTY;
        }

        Joiner joiner = Joiner.on(getSeparatorChars_stringToAnyListMapping());
        if (skipNullOnJoinString_stringToAnyListMapping()) {
            joiner = joiner.skipNulls();
        }
        return joiner.join(list);
    }

    /** String转List<Long> */
    default List<Long> stringToLongList(String val) {
        if (StringUtils.isBlank(val)) {
            return new ArrayList<>();
        }

        Splitter splitter = Splitter.on(getSeparatorChars_stringToAnyListMapping()).trimResults();
        if (omitEmptyStringsOnSplit_stringToAnyListMapping()) {
            splitter = splitter.omitEmptyStrings();
        }
        return splitter.splitToStream(val).map(Long::parseLong).collect(Collectors.toList());
    }

    /** List<Long>转String */
    default String longListToString(List<Long> list) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return StringUtils.EMPTY;
        }

        Joiner joiner = Joiner.on(getSeparatorChars_stringToAnyListMapping());
        if (skipNullOnJoinString_stringToAnyListMapping()) {
            joiner = joiner.skipNulls();
        }
        return joiner.join(list);
    }
}
